package com.it.you.service.pay;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 模板方法
 * <p>
 * 这段代码中先把实现了IPay接口的支付类实例初始化到一个list集合中，
 * 返回在调用支付接口时循环遍历这个list集合，如果code跟自己定义的一样，则调用当前的支付类实例的pay方法。
 * spring aop 实现思想
 */
@Service
public class PayService4 implements ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;
    private List<IPay> payList = null;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (payList == null) {
            payList = new ArrayList<>();
            Map<String, IPay> beansOfType = applicationContext.getBeansOfType(IPay.class);
            beansOfType.forEach((key, value) -> payList.add(value));
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public String pay(String code) {
        for (IPay iPay : payList) {
            if (iPay.support(code)) {
                return iPay.pay();
            }
        }
        return null;
    }

}
